package com.lcz.googleplay.manager;

import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 线程池管理类
 * Created by hp on 2016/11/1.
 */

public class ThreadManager {
    private static ThreadManager manager;
    private ThreadPoolProxy longPool;
    private ThreadPoolProxy shortPool;

    public ThreadManager() {
    }

    public static ThreadManager getInstance() {
        if (manager == null) {
            manager = new ThreadManager();
        }
        return manager;
    }

    /*连接网络，操作数据库等耗时操作*/
    public synchronized ThreadPoolProxy createLongPool() {
        if (longPool == null) {
            longPool = new ThreadPoolProxy(5, 10, 5000L);
        }

        return longPool;
    }

    /*读取本地等耗时较短的操作*/
    public synchronized ThreadPoolProxy createShortPool() {
        if (shortPool == null) {
            shortPool = new ThreadPoolProxy(3, 5, 5000L);
        }
        return shortPool;
    }

    /*线程代理*/
    public class ThreadPoolProxy {
        private ThreadPoolExecutor poolExecutor;
        private int corePoolSize;
        int maximumPoolSize;
        long keepAliveTime;

        public ThreadPoolProxy(int corePoolSize, int maximumPoolSize, long keepAliveTime) {
            this.corePoolSize = corePoolSize;
            this.maximumPoolSize = maximumPoolSize;
            this.keepAliveTime = keepAliveTime;
        }


        /*启动线程*/
        public void execute(Runnable runnable) {
            if (poolExecutor == null) {
                //核心线程大小；  核心池满后创建最大池；任务执行完成后，线程存活时间；时间单位；最大线程池满后，创建临时存放的线程
                // int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue
                poolExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize, 5000, TimeUnit.MILLISECONDS, new LinkedBlockingQueue<Runnable>(10));
            }
            poolExecutor.execute(runnable);
        }

        /*取消任务*/
        public void cancel(Runnable runnable) {
            if (poolExecutor != null && !poolExecutor.isShutdown() && !poolExecutor.isTerminated()) {
                poolExecutor.remove(runnable);
            }
        }
    }
}
